package com.anmory.imgrecognition;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@CrossOrigin(origins = "*") // 允许所有来源的跨域请求
@RequestMapping("/api")
public class RecognitionController {
    @PostMapping("/recognize")
    public String recognizeImage(@RequestParam("image") MultipartFile file) {
        try {
            // 保存上传的图片到临时文件
            String uploadDir = "uploads";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs();

            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path filePath = Paths.get(uploadDir, fileName);
            Files.write(filePath, file.getBytes());

            // 调用 Python 脚本
            ProcessBuilder processBuilder = new ProcessBuilder("python", "recognize/predict.py", filePath.toString());
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 读取 Python 脚本的输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            // 删除临时文件
            Files.deleteIfExists(filePath);
            // 返回识别结果
            return output.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "{\"error\": \"识别失败\"}";
        }
    }
}